import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Pagination, ConfirmService, ToastService, ModalService } from 'ng-tui';
import { ApiData, SearchParams } from '../../../../cores/classes';
import { GlobalService } from '../../../../cores/services';
// import { AccountService } from '../../services/account.service';
import { InventoryService } from '../../services/inventory.service';
import { PlatformManager } from './../../interfaces/platform.interfaces';
import { skipWhile, switchMap } from 'rxjs/operators';
import { ModalAccontComponent } from './modalaccount.component';
import { Inventory } from '../../interfaces/inventory.interfaces';

@Component({
    selector: 'app-account',
    templateUrl: './account.component.html',
    styleUrls: ['./account.component.scss']
})
export class AccountComponent implements OnInit {

    theads = ['#', '资产名称', '资产类型', '购买时间', '采购金额', '可用年限', '已用年限', '折旧方式', '剩余价值', '期初日期', '操作'];

    search = new SearchParams({ start: '', end: '' });

    list = new Array<PlatformManager>();

    loading = false;
    inventory: Inventory = { id: 0, beginOfPeriodDate: '' };
    pagination = new Pagination();

    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        public global: GlobalService,
        private confirm: ConfirmService,
        private inventoryService: InventoryService,
        private toast: ToastService,
        private modal: ModalService,
    ) { }

    ngOnInit() {
        this.activatedRoute.url
            .pipe(skipWhile(() => this.router.url !== '/admin/platform'))
            .subscribe(() => this.loadDatas());
            this.loadDatas();
    }

    doSearch() {
        this.pagination.reset();
        this.loadDatas();
    }

    doReset() {
        this.search.clean();
        this.doSearch();
    }

    loadDatas() {
        this.loading = true;
        this.inventoryService.searchPlatformManager(this.pagination, this.search).subscribe({
            next: res => {
                this.pagination.total = res.datas.total;
                this.list = res.datas.rows;
            },
            complete: () => this.loading = false
        });
    }

    confirmDelete(id: number) {
        this.confirm.danger('删除确认', `您确认删除资产数据'吗？`)
            .pipe(switchMap<void, ApiData>(() => this.inventoryService.deletestage(id)))
            .subscribe(() => {
                this.list.splice(this.list.indexOf(this.inventory), 1);
                this.toast.success('删除成功', `成功删除资产数据`);
                this.loadDatas();
            });
    }
    showEditModal(item: Inventory) {
        const modal = this.modal.create(ModalAccontComponent, { center: true });
        modal.instance.inventory = Object.assign(modal.instance.inventory, item);
        modal.open().subscribe(() => {
            this.toast.success('保存成功', '成功保存资产');
            this.loadDatas();
        });
    }
}
